package cn.anecansaitin.whimsy.common.item;

import cn.anecansaitin.whimsy.common.block.entity.RockAltarEntity;
import cn.anecansaitin.whimsy.common.register.ModBlocks;
import net.minecraft.core.BlockPos;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;

public class DioriteAltarBuilder extends Item {
    public DioriteAltarBuilder() {
        super(new Properties());
    }

    @Override
    public InteractionResult useOn(UseOnContext context) {
        BlockPos pos = context.getClickedPos();
        Level level = context.getLevel();
        boolean isAltar = level.getBlockState(pos).is(ModBlocks.ROCK_ALTAR.get());
        Player player = context.getPlayer();

        if (!isAltar && player == null) {
            return InteractionResult.PASS;
        }

        for (RockAltarEntity.Struct struct : RockAltarEntity.DIORITE_STRUCT) {
            BlockPos offset = pos.offset(struct.xOffset(), struct.yOffset(), struct.zOffset());

            if (!level.getBlockState(offset).isAir()) {
                continue;
            }

            if (!player.isCreative()) {
                Inventory inventory = player.getInventory();
                int slot = inventory.findSlotMatchingItem(new ItemStack(struct.block()));

                if (slot == -1) {
                    continue;
                }

                inventory.getItem(slot).split(1);
            }

            level.setBlock(offset, struct.block().defaultBlockState(), 2);
        }

        return InteractionResult.SUCCESS;
    }
}
